<?php

function sendMail($code, $to_email, $paras) {
    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
    if (!preg_match($pattern, $to_email)) {
        return array("code" => "email_error", "result" => "邮箱格式有误");
    }
    $template = getEmailContent($code, $paras);
    $subject = $template['title'];
    
    if ($code == 'goods_consult'){
        $body = $paras['consult_content']."<br>".$template['content'];
}else{
    $body = $template['content'];
}
$body = htmlspecialchars_decode($body);
//echo htmlspecialchars_decode($body);exit;
    $uid = $template['uid'];
    $config = getTableConfig();
    $detail = json_decode($config['email_config'], true);
    if ($detail['is_show'] == 1) {
        $title = C("title");
        vendor('phpmailer.class#phpmailer');
        $mail = new PHPMailer(); //PHPMailer对象
        $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
        $mail->IsSMTP();  // 设定使用SMTP服务
        $mail->SMTPDebug = 0;                     // 关闭SMTP调试功能
        $mail->SMTPAuth = true;                  // 启用 SMTP 验证功能
        $mail->SMTPSecure = '';                 // 使用安全协议
        $mail->Host = $detail['smpt'];  // SMTP 服务器
        $mail->Port = "25";  // SMTP服务器的端口号
        $mail->Username = $detail['account'];  // SMTP服务器用户名
        $mail->Password = $detail['pwd'];  // SMTP服务器密码
        $mail->Subject = $subject; //邮件标题
        $mail->SetFrom($detail['account'], $title);
        $mail->MsgHTML($body);
        $mail->AddAddress($to_email, $title);
        $result = $mail->Send() ? 'ok' : $mail->ErrorInfo;
        if ($code == 'goods_consult') {
            $paras['content'] =$body;
            addEmailGoods($paras);
        } else {
            addEmailRecord($uid, $code, $subject, $body, $to_email, $result);
        }

        $rs = array("code" => "0", "result" => $result);
    } else {
        $rs = array("code" => "email_not_start", "result" => "邮箱未开启");
    }
    return $rs;
}

function addEmailGoods($paras) {
    $data['uid'] = $paras['uid'];
    $data['goods_id'] = $paras['goods_id'];
    $data['email'] = $paras['email'];
    $data['content'] = $paras['content'];
    $data['addtime'] = time();
    M("goods_email")->add($data);
}

function addEmailRecord($uid,$code, $title, $content, $accounts, $error) {
    $data['code'] = $code;
    $data['title'] = $title;
    $data['content'] = $content;
    $data['accounts'] = $accounts;
    $data['uid'] = intval($uid);
    $data['error'] = $error;
    M("email_record")->add($data);
}

function getEmailState($error) {
    $rs = "发送失败<span  class='help-button' data-rel='popover' data-trigger='hover' data-placement='left' data-content='" . $error . "'>?</span>";
    if ($error == 'ok') {
        $rs = "<span class='green'>发送成功</span>";
    }
    return $rs;
}

function getEmailCode($code) {
    $arr = array(
        "reg_code" => "注册",
        "test" => "测试",
        "find_pwd_code" => "忘记密码"
    );
    if ($code) {
        return $arr[$code];
    } else {
        return $arr;
    }
}

function getEmailContent($code, $paras) {
    $rs = array();
    if ($code) {
        $detail = M("email_template")->field("title,content,is_show")->where("code ='" . $code . "'")->find();
        $content = $detail['content'];
        if ($detail['is_show'] == 1) {
//            print_r($paras);
            if ($paras) {
                foreach ($paras as $k => $v) {
                    $content = str_replace("{" . $k . "}", $v, $content);
                }
            }
            $rand = rand(1000, 9999);
            $content = str_replace("{rand}", $rand, $content);
            $time = date("m-d H:i:s");
            $content = str_replace("{time}", $time, $content);
            $rs['content'] = $content;
            $rs['title'] = $detail['title'];
        }
        return $rs;
    } else {
        return array("code" => "code_no_has", "result" => "缺少必要参数code");
    }
}

function checkSendEmailCode($email, $code, $code_post, $is_delete) {
    $detail = M("email_record")->field("content,id")->where("accounts = '" . $email . "' AND code ='" . $code . "'")->find();
    $code_save = preg_replace('/\D/', '', $detail['content']);
    $rs = array("code" => 0, "result" => "ok");
    if ($code_save != $code_post) {
        $rs = array("code" => "code_error", "result" => "邮箱验证码输入错误");
    } else {
        //验证通过，删除验证码
        if ($is_delete == 1) {
            M("email_record")->where("id = " . $detail['id'] . "")->delete();
        }
    }
    return $rs;
}
